const $sql = require('../sqlfun');//sql语句
var models = require('../connectmysql');//数据库链接信息
var mysql = require('mysql');
const fs = require('fs');
const formidable=require('formidable');
const path=require('path');
var sd = require("silly-datetime");
var conn = mysql.createConnection(models.mysql);
conn.connect();

module.exports = (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  //res.setHeader("Access-Control-Allow-Methods", "POST");
  console.log("临时缓存中");
  //检测文件夹是否存在
  let form=new formidable.IncomingForm();
  //解析内容
  form.parse(req,function(err,field,files) {//错误，传来的数据，文件
    if (err) {
      return res.json({
        "code": 500,
        "message": "内部服务器错误"
      })
    }
    let options = {
      fname: field.filename,
      ftype: field.filetype,
      fsize: field.filesize
    }
    console.log(files);
    console.log("params", options);

    var ran = parseInt(Math.random() * 8999 + 10000);
    var t = sd.format(new Date(), 'YYYYMMDDHHmmss');
    var extname = path.extname(files.upfile.name);
    var oldpath = files.upfile.path;
    var newpath = './UploadFile/' + t + ran + extname;
    var readStream = fs.createReadStream(oldpath);
    var writeStream = fs.createWriteStream(newpath);
    readStream.pipe(writeStream);
    return readStream.on('open', function () {
      fs.unlinkSync(oldpath);
      console.log("缓存成功");

      var sql = $sql.datames.addbbsimage;
      var params = req.body;
      console.log("sql", sql);
      console.log("params", params);
      var newname=t + ran + extname;
      conn.query(sql,[newpath,options.fname,newname], function(err, data) {
        if(err){
          var result={
            "status":"500",
            "message":"服务器错误",
            "data":err
          }
          console.log(result);
          res.send(result);
        }
        else {
          var result={
            "status":"200",
            "message":"success",
            data:data
          }
          console.log(result);
          res.send(result);
        }
    })

    });
  })
}
